package com.laviedesfons.jhmtasc.logging;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * An OutputStream that writes contents to a Logger upon each call to flush()
 *
 * @author Romano
 */
public class OutputStreamLogger extends ByteArrayOutputStream {

    private String lineSeparator;
    private Logger logger;
    private Level level;

    public OutputStreamLogger(Logger log, Level level) {
        super();
        this.level = level;
        this.logger = log;
        lineSeparator = System.getProperty("line.separator");
    }

    @Override
    public void flush() throws IOException {

        String record;
        synchronized (this) {
            super.flush();
            record = this.toString();
            super.reset();

            if (record.isEmpty() || record.equals(lineSeparator)) {
                // avoid empty records
                return;
            }
            int idx;
            if((idx = record.lastIndexOf("\n")) != -1){
                if(record.substring(idx).trim().isEmpty()){
                    record = record.substring(0, idx);
                }
            }

            logger.logp(level, "","",record);
        }
    }
}